<template>
  <div class="ticket-page">
    <ticket-tabbar :tabList="ticketTabList" :currentTab="currentTab" @change="tabChange"></ticket-tabbar>
    <scroll-view
      class="public_wrapper"
      :style="{ height: screenHeight }"
      scroll-y
      @refresherrefresh="reload"
      :refresher-triggered="triggered"
      @scrolltolower="loadData"
    >
      <div class="wrap" style="padding-top: 20rpx">
        <ticket-item v-for="(item, index) in list" :item="item" :key="item.id"> </ticket-item>
      </div>
      <uni-load-more :status="loading ? 'loading' : noMore ? 'noMore' : 'more'" />
    </scroll-view>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, watch, computed, defineExpose } from 'vue'

import { useStore } from 'vuex'
import TicketItem from './ticket-item.vue'
const store = useStore()
const screenHeight = ref<number>(0)
const statusBarHeight = computed(() => store.getters['system/statusBarHeight'])
const bottomSafeArea = computed(() => store.getters['system/bottomSafeArea'])
screenHeight.value = `calc(100vh - ${statusBarHeight.value}px - ${bottomSafeArea.value}px - 90rpx - 116rpx - 126rpx - 64rpx)`

import { exhibitionOrderList } from '@/utils/api/exhibition'
// 请求状态码，是否又更多
const loading = ref<boolean>(false)
const noMore = ref<boolean>(false)

interface TicketTabItem {
  value: number
  label: string
}
let ticketTabList = reactive<TicketTabItem[]>([
  {
    value: 2,
    label: '未使用 New'
  },
  {
    value: 3,
    label: '已使用 Used'
  },
  {
    value: 4,
    label: '已过期 Expired'
  }
])

// 订单列表
let list = ref<any[]>([])
// triggered:刷新的状态
let triggered = ref<boolean>(false)

// 显式声明并赋值
let current: number = 1

// 是否是重新加载
let isReload: boolean = false

let currentTab = ref<number>(0)
const tabChange = (index: number) => {
  currentTab.value = index
  console.log('接收到的下标', index)
  initData()
}

const loadData = async () => {
  if (loading.value || noMore.value) {
    return
  } else {
    loading.value = true
  }
  console.log('ticketTabList.value[currentTab.value]', ticketTabList, currentTab.value)
  const res = await exhibitionOrderList({
    current: current,
    status: ticketTabList[currentTab.value].value,
    size: 10
  })
  loading.value = false
  triggered.value = false
  console.log('刷新状态:', triggered.value)
  uni.stopPullDownRefresh()
  if (res.code === 200) {
    if (res.data.next) {
      current++
      noMore.value = false
    } else {
      noMore.value = true
    }
    if (isReload) {
      list.value = res.data.list
      console.log('刷新列表:', list.value)
      isReload = false
    } else {
      list.value = list.value.concat(res.data.list)
    }
  }
}

const initData = () => {
  console.log('票务初始化数据')
  isReload = true
  triggered.value = true
  current = 1
  noMore.value = false
  loadData()
}
onMounted(() => {
  initData()
})
defineExpose({
  initData
})
</script>

<style lang="scss" scoped>
@import './ticket.scss';
</style>
